<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="920px">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      :inline="true"
      label-width="auto"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="elderId">
            <el-input
              v-model="formData.elder.name"
              placeholder="请输入姓名"
              disabled
              class="mr-1"
            />
            <el-button @click="clickChooseElder">选择老人</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="identityCard">
            <el-input v-model="formData.elder.identityCard" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="缴费方式" prop="payType">
            <el-select v-model="formData.payType" placeholder="请输入缴费方式">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.FEE_PAY_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="缴费时间" prop="payTime">
            <el-date-picker
              v-model="formData.payTime"
              placeholder="请输入缴费时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form-item>
      <el-button @click="clickAddDeposit">添加押金</el-button>
      <el-button @click="clickDeleteDeposit">删除押金</el-button>
    </el-form-item>
    <Table
      :columns="columns"
      :adaptive="true"
      :data="formData.details"
      save-key="FeeDepositDetail"
      :row-style="rowStyle"
      @row-click="handleRowClick"
    >
      <template #feeCategoryId="{ row }">
        <el-select v-model="row.feeCategoryId" @change="handleFeeCategoryIdChange(row)">
          <el-option
            v-for="dict in categoryList"
            :key="dict.id"
            :label="dict.categoryName"
            :value="dict.id"
          />
        </el-select>
      </template>
      <template #depositFee="{ row }">
        <InputNumber type="decimal" class="!w-70px" v-model="row.depositFee" />
      </template>
      <template #description="{ row }">
        <el-input v-model="row.description" />
      </template>
    </Table>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <ElderInfoSelect ref="elderInfoSelectRef" @row-dblclick="handleSelectElderInfo" />
</template>
<script setup name="FeeDepositDetail" lang="ts">
import ElderInfoSelect from '@/views/elder/elderInfo/ElderInfoSelect.vue'
import * as FeeDepositApi from '@/api/fee/feeDeposit'
import * as FeeDepositDetailModel from '@/model/fee/deposit/FeeDepositDetail'
import * as FeeCategoryApi from '@/api/fee/feeCategory'
import { FeeCategoryTypeEnum } from '@/utils/constants'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
interface FeeDepositDetail {
  elderId: number | undefined
  elder: { name: string; identityCard: string }
  payType: number
  payTime: Date | undefined
  details: FeeDepositDetailModel.FeeDepositDetail[]
}
const categoryList = ref()
const elderInfoSelectRef = ref()
const message = useMessage()
const { t } = useI18n()
const dialogTitle = ref('交押金')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const formData = ref<FeeDepositDetail>({
  elderId: undefined,
  elder: { name: '', identityCard: '' },
  payType: 1,
  payTime: undefined,
  details: []
})
const formRules = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'change' }],
  payTime: [{ required: true, message: '请选择缴费时间', trigger: 'change' }]
})
const tableCurrentRow = ref()
const columns = [
  {
    label: '费用类别',
    prop: 'feeCategoryId',
    slot: 'feeCategoryId'
  },
  {
    label: '金额',
    prop: 'depositFee',
    slot: 'depositFee'
  },
  {
    label: '押金说明',
    prop: 'description',
    slot: 'description'
  }
]
/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  categoryList.value = await FeeCategoryApi.getByType(FeeCategoryTypeEnum.DEPOSIT)
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    elder: { name: '', identityCard: '' },
    elderId: undefined,
    payType: 1,
    payTime: undefined,
    details: []
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  let data = [] as FeeDepositDetailModel.FeeDepositDetail[]
  formData.value.details.forEach((detail) => {
    data.push({
      id: undefined,
      elderId: formData.value.elderId,
      payType: formData.value.payType,
      description: detail.description,
      depositFee: detail.depositFee,
      status: 1,
      payTime: formData.value.payTime,
      feeCategoryId: detail.feeCategoryId
    })
  })
  await FeeDepositApi.create(data)
  message.success(t('common.createSuccess'))
  dialogVisible.value = false
  // 发送操作成功的事件
  emit('success')
}

/** table行的style的回调方法 */
const rowStyle = ({ row }) => {
  if (row?.operateType == 'delete') {
    return { display: 'none' }
  } else return {}
}

/** table行点击事件 */
const handleRowClick = (row) => {
  tableCurrentRow.value = row
}

const clickChooseElder = () => {
  elderInfoSelectRef.value.open()
}

const handleSelectElderInfo = (selectElderInfo) => {
  formData.value.elder.name = selectElderInfo.name
  formData.value.elder.identityCard = selectElderInfo.identityCard
  formData.value.elderId = selectElderInfo.id
}

const clickAddDeposit = () => {
  formData.value.details.push({
    id: undefined,
    elderId: undefined,
    description: '',
    depositFee: 0,
    status: 1,
    payType: 1,
    payTime: undefined,
    feeCategoryId: undefined
  })
}

const clickDeleteDeposit = () => {
  const index = formData.value.details.indexOf(tableCurrentRow.value)
  formData.value.details.splice(index, 1)
}

const handleFeeCategoryIdChange = (row) => {
  categoryList.value.forEach((category) => {
    if (category.id == row.feeCategoryId) {
      row.depositFee = category.fee
    }
  })
}
</script>
